package com.feri.redromance01.controller;

import com.feri.redromance01.util.FileUtil;
import com.feri.redromance01.vo.R;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @autor wfl
 * @time 2022/8/30
 */
@RestController
@RequestMapping("/api/file/")
public class FileController {
@PostMapping("uploading.do")
    public R upload(MultipartFile file, HttpServletRequest request) throws IOException{
    //1.验证文件是否存在
    if (!file.isEmpty()){
        //2.获取上传文件名并完成重命名
        String fn = FileUtil.reName(file.getOriginalFilename());
        //3.获取上传的文件内容
        byte[] data = file.getBytes();
        //4.创建文件存储的文件夹
        File dir =new File(request.getServletContext().getRealPath("/upload"));
        if (!dir.exists()){
            dir.mkdirs();
        }
        //5.存储
        IOUtils.write(data,new FileOutputStream(new File(dir,fn)));
        //6.返回
        return R.ok("/upload"+fn);
    }else {
        return R.fail();
    }
}
}
